package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.entity.SysMenu;
import com.itheima.ydd.mapper.SysMenuMapper;
import com.itheima.ydd.service.ISysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {
    @Autowired
    private SysMenuMapper menuMapper;

    @Override
    public List<SysMenu> menuList(String role_id) {
        String[] strings = role_id.split(",");
        List<SysMenu> menuList = menuMapper.findMenuList(strings);
        return menuList;
    }

    /**
     * 查询所有菜单
     * @return
     */
    @Override
    public List<SysMenu> getMenu() {
        //储存所有数据
        List<SysMenu> menuList = this.list();

        List<SysMenu> menus = getMenuMethod(menuList);

        return menus;
    }

    /**
     * 删除菜单
     * @param id
     */
    @Override
    public void removePid(String id) {
        SysMenu menu = this.getById(id);
        LambdaQueryWrapper<SysMenu> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysMenu::getPid, menu.getId());
        //判断是否存在子菜单
        List<SysMenu> menuList = this.list(lqw);
        if (menuList.size() > 0) {
            throw new BusinessException("该菜单存在子菜单，禁止删除！");
        }

        this.removeById(id);
    }


    /**
     * 封装方法调取菜单信息
     * @param menuList
     * @return
     */
    public List<SysMenu> getMenuMethod(List<SysMenu> menuList){
        //存储处理好的数据
        ArrayList<SysMenu> menus = new ArrayList<>();

        //得到父节点
        for (SysMenu menu : menuList) {
            if (menu.getPid().equals(0)) {
                menus.add(menu);
            }
        }

        //子节点处理
        for (SysMenu menu : menus) {
            //绑定菜单
            List<SysMenu> children1 = new ArrayList<>();
            for (SysMenu menu1 : menuList) {
                if (menu1.getPid().equals(menu.getId())) {
                    children1.add(menu1);
                    menu.setChildren(children1);
                    //绑定按钮
                    List<SysMenu> children2 = new ArrayList<>();
                    for (SysMenu menu2 : menuList) {
                        if (menu2.getPid().equals(menu1.getId())) {
                            children2.add(menu2);
                            menu1.setChildren(children2);
                        }
                    }
                }
            }
        }
        return menus;
    }
}
